package com.ww.learn.uses

class NetworkConnection(private val host: String, private val port: Int) : AutoCloseable {
    init {
        println("Connected to $host:$port")
    }

    fun sendMessage(message: String) {
        println("Sending message: $message")
    }

    override fun close() {
        println("Closing the connection")
    }
}

// 使用自定义资源
fun processNetworkRequest() {
    NetworkConnection("http://www.baidu.com", 80).use { connection ->
        connection.sendMessage("Hello World")
        // 可能抛出异常的操作
        if (System.currentTimeMillis() % 2 == 0L) {
            throw RuntimeException("模拟异常")
        }
        connection.sendMessage("World")
    } // 无论是否发生异常，close()都会被调用
}

// 打印结果
//Connected to http://www.baidu.com:80
//Sending message: Hello World
//Closing the connection
//操作失败：模拟异常
//...
//Connected to http://www.baidu.com:80
//Sending message: Hello World
//Sending message: World
//Closing the connection
//...
//Connected to http://www.baidu.com:80
//Sending message: Hello World
//Closing the connection
//操作失败：模拟异常
//...
fun main() {
    repeat(3) {
        try {
            processNetworkRequest()
        } catch (e: Exception) {
            println("操作失败：${e.message}")
        }
        println("...")
    }
}